package cn.hx.admin.websocket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/ws/{userId}")
public class ChatServer {

    private static Map<String, Session> routeTab = new ConcurrentHashMap<>();
    ObjectMapper objectMapper=new ObjectMapper();

    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) throws IOException {

        routeTab.put(userId, session);
        System.out.println(routeTab);
        Message message = new Message();
        Set<String> strings = routeTab.keySet();

        message.setType(Message.MessageType.JOIN);
        message.setText(objectMapper.writeValueAsString(strings));
        sendAll(objectMapper.writeValueAsString(message));
    }

    @OnClose
    public void onClose(@PathParam("userId") String userId) throws IOException {
        routeTab.remove(userId);
        System.out.println(routeTab);
        Message message = new Message();
        Set<String> strings = routeTab.keySet();

        message.setType(Message.MessageType.LEAVE);
        message.setText(objectMapper.writeValueAsString(strings));
        sendAll(objectMapper.writeValueAsString(message));
    }
    public void sendAll(String message) throws IOException {
        System.out.println(message);
        for (String s : routeTab.keySet()) {
            Session session = routeTab.get(s);
            session.getBasicRemote().sendText(message);
        }
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        Message value = objectMapper.readValue(message, Message.class);
        String toUser = value.getToUser();
        if (StringUtils.hasText(toUser)){
            //给对方发
            Session session1 = routeTab.get(toUser);
            if (session1!=null&&session1.isOpen()){
                session1.getBasicRemote().sendText(message);
            }


            //给自己发送
            String name = value.getName();
            Session session2 = routeTab.get(name);
            if (session2!=null&&session2.isOpen()){
                session2.getBasicRemote().sendText(message);
            }

        }else {
            sendAll(message);
        }

    }

    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }
}